import './ItemScopePreview.css'
import EditIndustryScope from '@/views/ShoppingCart/components/EditIndustryScope.tsx'
import { useCallback, useEffect, useRef, useState } from 'react'
import type { MutableRefObject, ReactElement } from 'react'
import EditParkScope from '@/views/ShoppingCart/components/EditParkScope.tsx'
import EditCompanyScope from '@/views/ShoppingCart/components/EditCompanyScope.tsx'
import { Button, DatePicker, Typography } from 'antd'
import dayjs from 'dayjs'
import EditAreaScope from '@/views/ShoppingCart/components/EditAreaScope.tsx'
import { localShoppingData, tempData } from '@/views/ShoppingCart/LocalShoppingData.ts'
import { allAreaList, allCityList, allProvinceList } from '@hs-admin/utils'
import EditPolymerizeScope from '@/views/ShoppingCart/components/EditPolymerizeScope.tsx'

const { Text } = Typography

enum EnumScope {
  industry = 'industry',
  area = 'area',
  park = 'park',
  company_list = 'company_list',
  time = 'time',
  polymerize = 'polymerize'
}

const getAreaName = (code: string) => {
  if (code.slice(-2) === '00') {
    if (code.slice(-4) === '0000') {
      return allProvinceList.find((it) => it.value === code)?.label ?? '未知'
    } else {
      return allCityList[`${code.slice(0, 2)}0000`].find((it) => it.value === code)?.label ?? '未知'
    }
  } else {
    return allAreaList[`${code.slice(0, 4)}00`]?.find((it) => it.value === code)?.label ?? '未知'
  }
}

const commonScopes: Array<{
  name: string
  type: EnumScope
  key: string
  children: ReactElement | string
  emptyText: string
}> = [
  {
    name: '产业范围',
    type: EnumScope.industry,
    key: EnumScope.industry,
    children: '',
    emptyText: ''
  },
  {
    name: '区域范围',
    type: EnumScope.area,
    key: EnumScope.area,
    children: '',
    emptyText: ''
  },
  {
    name: '园区范围',
    type: EnumScope.park,
    key: EnumScope.park,
    children: '',
    emptyText: ''
  },
  {
    name: '企业白名单范围',
    type: EnumScope.company_list,
    key: EnumScope.company_list,
    children: '',
    emptyText: ''
  }
]

type EditRefType = MutableRefObject<{ showModal: () => void } | null | undefined>

const TimePicker = ({ id, disabled = false }: { id: string; disabled?: boolean }) => {
  const data = tempData('time') ?? {}
  const time1 = data?.[id]?.['time1']
  const time2 = data?.[id]?.['time2']

  const [time, setTime] = useState<{
    time1: null | undefined | string
    time2: null | undefined | string
  }>({
    time1: null,
    time2: null
  })

  useEffect(() => {
    setTime({
      time1,
      time2
    })
  }, [id])

  return (
    <div className="flex gap-8">
      <div className="flex gap-2 items-center">
        <span className="ws-nowrap">起始日期</span>
        <DatePicker
          disabled={disabled}
          value={time.time1 && dayjs(time.time1)}
          onChange={(val) => {
            if (val) {
              const time1 = dayjs(val).format('YYYY-MM-DD HH:mm:ss')
              tempData({
                time: {
                  ...data,
                  [id]: {
                    time1,
                    time2
                  }
                }
              })
              setTime((prevState) => ({
                ...prevState,
                time1
              }))
            } else {
              if (data[id]) {
                tempData({
                  time: {
                    ...data,
                    [id]: {
                      time1: undefined,
                      time2: undefined
                    }
                  }
                })
                setTime({
                  time1: null,
                  time2: null
                })
              }
            }
          }}
          showTime={{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }}
        />
      </div>
      <div className="flex gap-2 items-center">
        <span className="ws-nowrap">截止日期</span>
        <DatePicker
          disabled={disabled}
          value={time.time2 && dayjs(time.time2)}
          onChange={(val) => {
            if (val) {
              const time2 = dayjs(val).format('YYYY-MM-DD HH:mm:ss')
              tempData({
                time: {
                  ...data,
                  [id]: {
                    time1,
                    time2
                  }
                }
              })
              setTime((prevState) => ({
                ...prevState,
                time2
              }))
            } else {
              if (data[id]) {
                tempData({
                  time: {
                    ...data,
                    [id]: {
                      time1,
                      time2: undefined
                    }
                  }
                })
                setTime((prevState) => ({
                  ...prevState,
                  time2: null
                }))
              }
            }
          }}
          showTime={{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }}
        />
      </div>
    </div>
  )
}

export const ItemScopePreview = ({
  itemId,
  extraField,
  emptyText,
  onDone,
  disabled = false
}: {
  itemId: string
  extraField: {
    industry?: string
    area?: string
    park?: string
    company_list?: string
    polymerize: Array<{
      label: string
      id: string
    }>
    time: Array<{
      label: string
      id: string
    }>
  }
  emptyText: string
  onDone?: () => void
  disabled?: boolean
}) => {
  const editMap: EditRefType = useRef(null)
  const editPark: EditRefType = useRef(null)
  const editCompany: EditRefType = useRef(null)
  const editArea: EditRefType = useRef(null)
  const editPolymerize: EditRefType = useRef(null)
  const [itemScopes, setItemScopes] = useState(commonScopes)

  const [activePolymerize, setActivePolymerize] = useState({
    label: '',
    id: ''
  })

  const refMap: Record<EnumScope, EditRefType> = {
    industry: editMap,
    area: editArea,
    park: editPark,
    company_list: editCompany,
    polymerize: editPolymerize
  }

  const done = useCallback(() => {
    let data = localShoppingData(itemId)

    if (itemId !== 'common') {
      data = tempData()
    } else {
      localShoppingData('common', {
        p1: !!data?.['mapList']?.length,
        p2: !!data?.['areaList']?.length,
        p3: !!data?.['parkList']?.length,
        p4: !!data?.['companyInfo']?.id
      })
    }

    let showData = [
      {
        name: '产业范围',
        type: EnumScope.industry,
        key: EnumScope.industry,
        children: data?.['mapList']?.map((item) => <div key={item.id}>{item.name}</div>) ?? (data?.['p1'] && emptyText),
        emptyText: data?.['p1'] ? emptyText : '不限'
      },
      {
        name: '区域范围',
        type: EnumScope.area,
        key: EnumScope.area,
        children: data?.['areaList']?.map((it) => <div key={it}>{getAreaName(it)}</div>) ?? (data?.['p2'] && emptyText),
        emptyText: data?.['p2'] ? emptyText : '不限'
      },
      {
        name: '园区范围',
        type: EnumScope.park,
        key: EnumScope.park,
        children: data?.['parkList']?.map((item) => <div key={item.value}>{item.label}</div>) ?? (data?.['p3'] && emptyText),
        emptyText: data?.['p3'] ? emptyText : '不限'
      },
      {
        name: '企业白名单范围',
        type: EnumScope.company_list,
        key: EnumScope.company_list,
        children: data?.['companyInfo']?.count ? `${data?.['companyInfo']?.count}家` : data?.['p4'] && emptyText,
        emptyText: data?.['p4'] ? emptyText : '无'
      }
    ]

    if (extraField.time?.length) {
      showData = showData.concat(
        extraField.time.map((item) => ({
          name: item.label,
          type: 'time',
          key: item.id,
          children: <TimePicker id={item.id} disabled={disabled} />
        }))
      )
    }

    if (extraField.polymerize?.length) {
      showData = showData.concat(
        extraField.polymerize.map((item) => ({
          name: item.label,
          type: 'polymerize',
          key: item.id,
          children: data?.['polymerizeList']?.[item.id]?.map((item) => <div key={item}>{item}</div>) ?? '不限',
          emptyText: '不限'
        }))
      )
    }

    setItemScopes(showData)
  }, [emptyText, extraField.polymerize, extraField.time, itemId])

  useEffect(() => {
    if (itemId) {
      done()
    }
  }, [done, itemId])

  const doUpdate = useCallback(() => {
    setTimeout(() => {
      done()
      onDone?.()
    }, 10)
  }, [done, onDone])

  return (
    <div className="item-scope-wrapper">
      <div className="my-title-blue-before flex items-end m-b-4">
        {itemId === 'common' ? '整体范围选择' : '选择数据范围'}
        {itemId === 'common' && <p className="text-sm text-gray-5">(其他维度在各表中“编辑”操作中单独编辑)</p>}
      </div>
      {itemScopes.map((scope) => (
        <div key={scope.key} className="item-config">
          <div className="line-title">
            <Text
              ellipsis={{ tooltip: true }}
              style={{
                maxWidth: '7em'
              }}>
              {scope.name}
            </Text>
            {scope.type !== 'time' && (
              <Button
                type="link"
                onClick={() => {
                  if (scope.type === 'polymerize') {
                    setActivePolymerize({
                      label: scope.name,
                      id: scope.key
                    })
                    setTimeout(() => {
                      refMap[scope.type]?.current?.showModal()
                    }, 80)
                  } else {
                    refMap[scope.key]?.current?.showModal()
                  }
                }}
                disabled={!extraField[scope.type]}>
                {disabled ? '查看>>' : '去编辑>>'}
              </Button>
            )}
          </div>
          <div className="filter-line">
            {extraField[scope.type]
              ? Array.isArray(scope.children)
                ? scope.children.length
                  ? scope.children
                  : scope.emptyText
                : scope.children || scope.emptyText
              : '不可选'}
          </div>
        </div>
      ))}
      <EditIndustryScope ref={editMap} itemId={itemId} done={doUpdate} disabled={disabled} />
      <EditParkScope ref={editPark} itemId={itemId} done={doUpdate} disabled={disabled} />
      <EditCompanyScope ref={editCompany} itemId={itemId} done={doUpdate} disabled={disabled} />
      <EditAreaScope ref={editArea} areaLevel={extraField.area} itemId={itemId} done={doUpdate} disabled={disabled} />
      <EditPolymerizeScope ref={editPolymerize} itemId={itemId} done={doUpdate} polymerizeInfo={activePolymerize} disabled={disabled} />
    </div>
  )
}

export default ItemScopePreview
